<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h4 class="mb-0">错题本</h4>
        <button id="clearWrongQuestions" class="btn btn-danger" >清空错题本</button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>题目</th>
                        <th>分类</th>
                        <th>难度</th>
                        <th>正确答案</th>
                        <th>加入时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="questionList">
                    <!-- 错题列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center" id="pagination">
                <!-- 分页将通过JavaScript动态加载 -->
            </ul>
        </nav>
    </div>
</div>

<script>
$(document).ready(function() {
    var currentPage = 1;
    var pageSize = 10;

    // 加载错题列表
    function loadQuestions(page) {
        $.get('${pageContext.request.contextPath}/wrong-question/api/list', {
            page: page,
            size: pageSize
        }, function(response) {
            if (response.code === 200) {
                var questions = response.data.list;
                var total = response.data.total;
                var html = '';

                questions.forEach(function(question) {
                    html += '<tr>';
                    html += '<td>' + question.questionTitle + '</td>';
                    html += '<td>' + question.categoryName + '</td>';
                    html += '<td>' + getDifficultyLabel(question.difficulty) + '</td>';
                    html += '<td>' + question.answer + '</td>';
                    html += '<td>' + formatDate(question.createdAt) + '</td>';
                    html += '<td>';
                    html += '<a href="${pageContext.request.contextPath}/question/detail/' + question.questionId + '" class="btn btn-sm btn-primary me-1">重新答题</a>';
                    html += '<button class="btn btn-sm btn-danger deleteQuestion"  data-id="'+ question.id +'">移除</button>';
                    html += '</td>';
                    html += '</tr>';
                });

                $('#questionList').html(html);
                updatePagination(page, Math.ceil(total / pageSize));
            }
        });
    }

    // 更新分页
    function updatePagination(currentPage, totalPages) {
        var html = '';

        // 上一页
        html += '<li class="page-item ' + (currentPage <= 1 ? 'disabled' : '') + '">';
        html += '<a class="page-link" href="#" data-page="' + (currentPage - 1) + '" aria-label="Previous">';
        html += '<span aria-hidden="true">&laquo;</span></a></li>';

        // 页码
        for (var i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                html += '<li class="page-item active"><span class="page-link">' + i + '</span></li>';
            } else {
                html += '<li class="page-item"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
            }
        }

        // 下一页
        html += '<li class="page-item ' + (currentPage >= totalPages ? 'disabled' : '') + '">';
        html += '<a class="page-link" href="#" data-page="' + (currentPage + 1) + '" aria-label="Next">';
        html += '<span aria-hidden="true">&raquo;</span></a></li>';

        $('#pagination').html(html);
    }

    // 获取难度标签
    function getDifficultyLabel(difficulty) {
        switch(difficulty) {
            case 1: return '<span class="badge bg-success">简单</span>';
            case 2: return '<span class="badge bg-warning">中等</span>';
            case 3: return '<span class="badge bg-danger">困难</span>';
            default: return '<span class="badge bg-secondary">未知</span>';
        }
    }

    // 格式化日期
    function formatDate(timestamp) {
        if (!timestamp) return '-';
        var date = new Date(timestamp);
        return date.getFullYear() + '-' +
               padZero(date.getMonth() + 1) + '-' +
               padZero(date.getDate()) + ' ' +
               padZero(date.getHours()) + ':' +
               padZero(date.getMinutes());
    }

    // 删除错题
    function deleteQuestion(id) {
        if (confirm('确定要从错题本中移除这道题目吗？')) {
            $.ajax({
                url: '${pageContext.request.contextPath}/wrong-question/api/delete/' + id,
                type: 'DELETE',
                success: function(response) {
                    if (response.code === 200) {
                        loadQuestions(currentPage);
                    } else {
                        alert(response.message);
                    }
                }
            });
        }
    }

    // 清空错题本
    function clearWrongQuestions() {
        if (confirm('确定要清空错题本吗？此操作不可恢复！')) {
            $.ajax({
                url: '${pageContext.request.contextPath}/wrong-question/api/clear',
                type: 'DELETE',
                success: function(response) {
                    if (response.code === 200) {
                        loadQuestions(1);
                    } else {
                        alert(response.message);
                    }
                }
            });
        }
    }

    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }

    // 绑定分页点击事件
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = $(this).data('page');
        if (page > 0) {
            currentPage = page;
            loadQuestions(currentPage);
        }
    });

    $("#clearWrongQuestions").click(function (){
        clearWrongQuestions();
    })

    $(document).on('click', '.deleteQuestion', function() {
        console.log($(this));
        deleteQuestion($(this).data('id'));
    });

    // $(".deleteQuestion").click(function (){
    //     console.log($(this));
    //     deleteQuestion($(this).attr('data-id'));
    // });

    // 初始化
    loadQuestions(currentPage);
});


</script>
